import subprocess
import os
import numpy as np

# # 定义超参数和其他常量
lambda1 = [0.01, 0.1, 1, 10, 100]
lambda2 = [0.01, 0.1, 1, 10, 100]
dataset = "cora_smll"
alpha = 1
use_DVD = 1
# 设置可用的cuda设备编号
cuda_visible_devices = 0
# alpha=1 & use_DVD=1 for GNN_DVD, alpha=0 & use_DVD=1 for GNN_VD, use_DVD=0 for GNN only

# 检查目录是否存在
output_dir = "./results"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

for i in lambda1:
    for j in lambda2:
        for k in range(10):
            try:
                # subprocess.run("CUDA_VISIBLE_DEVICES=1 python3 train.py --dataset=pubmed --lambda1="+str(i)+" --lambda2="+str(j)+" --use_DVD="+str(1)+ " --use_alpha="+str(1), shell=True)
                # 运行训练脚本
                subprocess.run(
                    f"CUDA_VISIBLE_DEVICES={cuda_visible_devices} python train.py --dataset={dataset} --lambda1={i} --lambda2={j} --use_DVD={use_DVD} --use_alpha={alpha}",
                    shell=True, check=True)
            except subprocess.CalledProcessError as e:
                print(f"训练过程出错：{e}")
                continue

        try:
            # 读取结果文件
            with open(f"./{dataset}{alpha}.txt", "r") as f:
                ff = f.readlines()
        except FileNotFoundError:
            print(f"文件 {dataset}{alpha}.txt 未找到，跳过此组合。")
            continue

        # f = open("./"+ str(dataset)+"_base"+".txt","r")

        # 解析结果
        poly = []
        for line in ff:
            one = line.strip().split()
            poly.append(float(one[0]))

        poly = np.array(poly)
        mean_poly = poly.mean()
        std_poly = poly.std()
        print(mean_poly, std_poly)

        # 写入结果到汇总文件
        with open(f"{output_dir}/{dataset}{alpha}_all.txt", "a") as f:
            f.write(f"{i}\t{j}\t{mean_poly}\t{std_poly}\n")

        # 删除临时文件
        os.remove(f"./{dataset}{alpha}.txt")
